//
//  JTLoadingView.swift
//  TestUIKit
//
//  Created by Kiyo on 2021/4/20.
//

import UIKit

public class JTLoadingView: UIView {

    private lazy var indicator: UIActivityIndicatorView = {
        let idc = UIActivityIndicatorView(style: .white)
        return idc
    }()
    
    private lazy var messageLabel: UILabel = {
        let lbl = UILabel(frame: .zero)
        lbl.textColor = .white
        lbl.font = UIFont.systemFont(ofSize: 13)
        lbl.textAlignment = .left
        lbl.numberOfLines = 0
        return lbl
    }()
    
    private var loadingText: String?
    
    public var contentInset: UIEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    public var space: CGFloat = 10
    
    
    
    init(text: String? = nil) {
        
        var rect: CGRect
        if let msg = text {
            let size = msg.sizeForText(font: UIFont.systemFont(ofSize: 13), availableWidth: UIScreen.main.bounds.width * 0.65)
            rect = CGRect(x: 0, y: 0, width: size.width + contentInset.horizontalValue + space + 20, height: size.height + contentInset.verticalValue)
        }
        else {
            rect = CGRect(x: 0, y: 0, width: 50, height: 50)
        }
        
        super.init(frame: rect)
        
        loadingText = text
        setupSubviews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupSubviews() {
        
        layer.cornerRadius = 3
        backgroundColor = .black
        
        indicator.translatesAutoresizingMaskIntoConstraints = false
        indicator.startAnimating()
        
        messageLabel.text = loadingText
        
        if let msg = loadingText {
            let size = msg.sizeForText(font: UIFont.systemFont(ofSize: 13), availableWidth: UIScreen.main.bounds.width * 0.65)
            indicator.center = CGPoint(x: contentInset.left + indicator.frame.width/2, y: center.y)
            messageLabel.frame = CGRect(x: indicator.frame.maxX + space, y: 0, width: size.width, height: frame.height)
        }
        else {
            indicator.center = center
        }
        
        addSubview(indicator)
        addSubview(messageLabel)
    }
}
